package com.cmbird;

import com.cmbird.utils.DownloadUtils;
import com.cmbird.utils.MessageUtils;
import com.cmbird.utils.ZipUtils;
import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        try {
            String url = "";
            String jarName = "";
            String modulePath = "";
            String addModules = "";
            String vm = "";
            for (String arg : args) {
                if (arg.contains("url=")) {
                    url = arg.substring(arg.indexOf("=")+1);
                }else if(arg.contains("jarName=")){
                    jarName = arg.substring(arg.indexOf("=")+1);
                }else if(arg.contains("modulePath=")){
                    modulePath = arg.substring(arg.indexOf("=")+1);
                }else if(arg.contains("addModules=")){
                    addModules = arg.substring(arg.indexOf("=")+1);
                }else if(arg.contains("vm=")){
                    vm = arg.substring(arg.indexOf("=")+1);
                }
            }

            // 获取系统版本
            String osName=System.getProperty("os.name");
            MessageUtils.alert(50,"正在检查更新,请稍后");
            String fileName = DownloadUtils.downloadNet(url);
            // 判断 fileName 是否以 .jar 结尾的
            if(fileName.endsWith(".zip")){
                ZipUtils.unzip(fileName,"./");
            }
            if(osName.contains("Windows")){
                if(jarName.endsWith(".jar")){
                    Runtime.getRuntime().exec("cmd /c start javaw -jar "+vm+" "+jarName);
                }else if(jarName.endsWith(".exe")){
                    Runtime.getRuntime().exec("cmd /c start "+jarName);
                }
            }else {
                if("".equals(modulePath)){
                    Runtime.getRuntime().exec(new String[] {"/bin/sh","-c","java -jar "+jarName});
                }else {
                    Runtime.getRuntime().exec(new String[] {"/bin/sh","-c","java --module-path "+modulePath+" --add-modules "+addModules+" -jar "+jarName});
                }
            }
            // 两秒后关闭该对话框
            new Timer(2000, e -> System.exit(0)).start();
        } catch (Exception e) {
            MessageUtils.alert(36,"更新失败!!"+e.getMessage());
            new Timer(10000, s -> System.exit(0)).start();
            throw new RuntimeException(e);
        }
    }


}